package jp.ne.iforce.android.cameratest;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

public class AutoFocusPreview extends CameraPreview {
	AutoFocusPreview(Context context) {
		super(context);
	}

	void autoFocus() {
		camera.autoFocus(new AutoFocusCallback() {
			public void onAutoFocus(boolean success, final Camera camera) {




				ShutterCallback shutter = new ShutterCallback() {
					public void onShutter() {
						Log.d("TEST", "onShutter");
					}
				};

				PictureCallback raw = new PictureCallback() {
					public void onPictureTaken(byte[] data, Camera camera) {
						Log.d("TEST", "onPictureTaken: raw: data=" + data);
					}
				};

				PictureCallback jpeg = new PictureCallback() {

					public void onPictureTaken(byte[] data, final Camera camera) {
						Log.d("TEST", "onPictureTaken: jpeg: data=" + data);

						// オプションでサイズを指定してBitmapオブジェクトを生成
						BitmapFactory.Options opts = new BitmapFactory.Options();
						opts.inSampleSize = 2;
						Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,opts);
						// BinaryBitmapオブジェクトを生成
						LuminanceSource source = new RGBLuminanceSource(bitmap);
						BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

						// マルチフォーマット対応の入力ストリームを生成
				        Reader reader = new MultiFormatReader();

						try {
							//デコード
							Result result = reader.decode(binaryBitmap);
							// 結果を表示
					        BarcodeFormat format = result.getBarcodeFormat();
					        Log.d("TEST","フォーマット: " + format + "\n");
					        Log.d("TEST","コンテンツ:"+ result.getText() + "\n");

					        Toast.makeText(context, result.getText() , Toast.LENGTH_LONG).show();

						} catch (NotFoundException e1) {
							Log.d("TEST",e1.toString());
						} catch (ChecksumException e1) {
							Log.d("TEST",e1.toString());
						} catch (FormatException e1) {
							Log.d("TEST",e1.toString());
						}

						autoFocus();






					}
				};

				camera.takePicture(shutter, raw, jpeg);



			}
		});
	}

	void cancelAutoFocus() {
		camera.cancelAutoFocus();
	}


	public boolean onTouchEvent(MotionEvent event) {
		autoFocus();
		return true;
	}
}
